package com.sense.kukoo.biz_media.view

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.sense.feel.common.utils.ToastUtils
import com.sense.kukoo.biz_media.R
import com.sense.kukoo.biz_media.adapter.MediaListDetailAdapter
import com.sense.kukoo.biz_media.databinding.BizMediaActivityMediaListDetailBinding
import com.sense.kukoo.biz_media.vm.MediaDetailViewModel
import com.sense.kukoo.common.constant.ARouterUrl
import com.sense.kukoo.common.event.LoginSuccessEvent
import com.sense.kukoo.common.event.LogoutEvent
import com.sense.kukoo.common.event.SubscriptionChangedEvent
import com.sense.kukoo.common.media.Kukoo
import com.sense.kukoo.common.media.bean.LocalMediaListItemBean
import com.sense.kukoo.common.media.watcher.UserWatcher
import com.sense.kukoo.common.mvvm.view.BaseMvvmActivity
import com.sense.kukoo.common.repo.bean.BookBean
import com.sense.kukoo.common.repo.bean.BookDetailsBean
import com.sense.kukoo.common.repo.bean.BookItemBean
import com.sense.kukoo.common.repo.bean.MediaListDetailItemBean
import com.sense.kukoo.common.utils.ApplicationContext
import com.sense.kukoo.common.wiget.dialog.BottomLoginDialog
import com.sense.kukoo.common.wiget.dialog.BottomReportDialog
import com.sense.kukoo.common.wiget.dialog.ContentAgreementPopupWindow
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@Route(path = ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_LIST_DETAIL_ACTIVITY)
class MediaDetailActivity : BaseMvvmActivity<MediaDetailViewModel, BizMediaActivityMediaListDetailBinding>() {

    private val TAG: String = javaClass.simpleName

    private lateinit var mAdapter: MediaListDetailAdapter

    private var flagToRefresh:Boolean = false
    private var mCurrentMusic: LocalMediaListItemBean? = null
    private var mCurrentState: Int = UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING

    @JvmField
    @Autowired(name = ARouterUrl.KEY_BOOK_ID_STR)
    var bookId: String? = null

    override fun getLayoutId(): Int = R.layout.biz_media_activity_media_list_detail

    override fun getViewModelClass(): Class<MediaDetailViewModel> = MediaDetailViewModel::class.java

    override fun responseVM(action: Int) {}

    override fun initData() {
        ARouter.getInstance().inject(this)
        //
        mBinding.lifecycleOwner = this
        mBinding.vm = mViewModel
        setSupportActionBar(mBinding.toolBar)
        //
        mViewModel.setFromData(bookId!!)
        //
        bindAction(mViewModel.action_back) {
            finish()
        }
        bindAction(mViewModel.action_more) {
            BottomReportDialog(this).setListener {
                mViewModel.report(it)
            }.show()
        }
        bindAction(mViewModel.action_reportSuccess){
            ToastUtils.showToast(ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.report_thanks_hint))
        }
        bindAction(mViewModel.action_download) {
            ToastUtils.showToast("download")
        }
        bindAction(mViewModel.action_share) {
            val alias : String = mViewModel.mData?.alias.toString()
            val type : Int = mViewModel.mData?.type ?: -1
            val subTitle : String = mViewModel.mData?.alias.toString()
            val author : String = mViewModel.mData?.author.toString()
            val bookUrl : String = mViewModel.mData?.coverUrl.toString()
            val imgUrl : String = mViewModel.mData?.coverUrl.toString()
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_SHARE_MODULE_SHARE_ACTIVITY)
                .withString(ARouterUrl.KEY_SHARE_BOOK_TITLE, alias)
                .withInt(ARouterUrl.KEY_SHARE_BOOK_TYPE, type)
                .withString(ARouterUrl.KEY_SHARE_BOOK_SUB_TITLE, subTitle)
                .withString(ARouterUrl.KEY_SHARE_BOOK_AUTHOR, author)
                .withString(ARouterUrl.KEY_SHARE_BOOK_URL, bookUrl)
                .withString(ARouterUrl.KEY_SHARE_BOOK_IMAGE_URL, imgUrl)
                .navigation()
        }
        bindData(mViewModel.enableLoadMore) {
            mBinding.refreshLayout.setEnableLoadMore(it)
        }
        bindData(mViewModel.mMediaListData) {
            mBinding.refreshLayout.finishRefresh()
            mBinding.refreshLayout.finishLoadMore()
            mAdapter.list = it
            mAdapter.notifyDataSetChanged()
        }
    }

    override fun initView() {
        mAdapter = MediaListDetailAdapter(mListener, arrayListOf())
        mBinding.recyclerView.adapter = mAdapter

        val linearLayoutManager = LinearLayoutManager(this)
        mBinding.recyclerView.layoutManager = linearLayoutManager
        mBinding.refreshLayout.setOnRefreshListener {
            //OnRefresh
            mViewModel.refreshData()
        }
        mBinding.refreshLayout.setOnLoadMoreListener {
            //OnLoadMore
            mViewModel.loadMore()
        }
        //
        mViewModel.refreshData()
    }

    override fun onResume() {
        super.onResume()
        if (flagToRefresh) {
            flagToRefresh = false
            mViewModel.refreshData()
        }
    }

    private val mListener = object : MediaListDetailAdapter.MediaListListener {

        override fun onBtnListenClick(bean: MediaListDetailItemBean) {
            //play now 按钮
            val detail: BookDetailsBean = bean.bean!!
            val bookItemBean: BookItemBean = detail.bookItems!![0]
            if (detail.type== BookBean.TYPE_PODCAST) {
                //播客
                ToastUtils.showToast("todo play now-click - ${bean.bookItems?.name}")
            }else{
                //
                if(mCurrentMusic != null && mCurrentMusic?.idOfBooks() == mViewModel.mData?.idOfBook()){
                    //相同
                    when (mCurrentState) {
                        UserWatcher.MusicStateWatcher.STATE_PREPARE,
                        UserWatcher.MusicStateWatcher.STATE_ERROR_RETRYING,
                        UserWatcher.MusicStateWatcher.STATE_SEEKING,
                        UserWatcher.MusicStateWatcher.STATE_PLAYING ->{
                            Kukoo.input.pause()
                        }
                        UserWatcher.MusicStateWatcher.STATE_PAUSE ->{
                            Kukoo.input.start()
                        }
                        else ->{
                            playMusic(detail, bookItemBean)
                        }
                    }
                }else{
                    //不同
                    playMusic(detail, bookItemBean)
                }
            }
        }

        override fun onBtnQuestionClick(question: View) {
            ContentAgreementPopupWindow.create(this@MediaDetailActivity, null)
                .show(question)
        }

        override fun onBtnSubscribeClick(bean: MediaListDetailItemBean) {
            //未登陆不能进行订阅
            if (BottomLoginDialog.autoCheckAndLogin(this@MediaDetailActivity)){
                mViewModel.subscription()
            }
        }

        override fun onBtnSortClick(bean: MediaListDetailItemBean) {
            mViewModel.reverseSort()
        }

        override fun onBtnMediaItemClick(bean: MediaListDetailItemBean) {
            val data:BookDetailsBean = bean.bean!!
            val bookItems: BookItemBean = bean.bookItems!!
            if(data.type == BookBean.TYPE_PODCAST){
                //博客,播放或暂停
                if(mCurrentMusic!=null && mCurrentMusic?.idOfBooks()==bookItems.bookId && mCurrentMusic?.idOfChapter()==bookItems.id){
                    //当前播放的
                    when (mCurrentState) {
                        UserWatcher.MusicStateWatcher.STATE_PREPARE,
                        UserWatcher.MusicStateWatcher.STATE_ERROR_RETRYING,
                        UserWatcher.MusicStateWatcher.STATE_SEEKING,
                        UserWatcher.MusicStateWatcher.STATE_PLAYING -> {
                            Kukoo.input.pause()
                        }
                        /*UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING ->{}
                        UserWatcher.MusicStateWatcher.STATE_PAUSE ->{}*/
                        else -> {
                            Kukoo.input.start()
                        }
                    }
                } else {
                    playMusic(bean.bean!!, bean.bookItems!!)
                }
            }else{
                //其它类型的item点击
                playMusic(bean.bean!!, bean.bookItems!!)
                //打开播放页
                ARouter.getInstance()
                    .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_CONTROLER_ACTIVITY)
                    .navigation()
            }
        }

        override fun onBtnPodcastItemClick(bean: MediaListDetailItemBean) {
            //播客item点击，进入博客详情
            val detail = bean.bean
            /*val data = LocalMediaListItemBean()
            data.book = bean.bookItems
            data.mCoverUrl = detail?.coverUrl
            data.name = detail?.name
            data.isSubscription = detail?.isSubscription
            data.chapterTotal = detail?.chapterTotal
            data.isChapter = detail?.isChapter
            data.type = detail?.type ?: 0
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_MEDIA_MODULE_PODCAST_DETAIL_ACTIVITY)
                .withInt(ARouterUrl.KEY_FROM, 2)
                .withParcelable(ARouterUrl.KEY_LOCAL_MEDIA_LIST_ITEMBEAN, data)
                .navigation()*/
        }
    }

    private fun playMusic(detail: BookDetailsBean, bookItemBean: BookItemBean){
        /*val data = LocalMediaListItemBean()
        data.book = bookItemBean
        data.mCoverUrl = detail.coverUrl
        data.name = detail.name
        data.isSubscription = detail.isSubscription
        data.chapterTotal = detail.chapterTotal
        data.isChapter = detail.isChapter
        data.type = detail.type ?: 0

        Kukoo.input.play(data)*/
    }

    private val mWatcher = object : UserWatcher.MusicStateWatcher {

        override fun onMusicChanged(music: LocalMediaListItemBean) {
            mCurrentMusic = music
            mAdapter.setCurrentMusic(music)
            /*mCurrentMusic = music
            if(mCurrentMusic != null && mCurrentMusic?.idOfBooks() == mViewModel.mData?.idOfBook()){
                //
            }*/
        }

        override fun onPlayTimeChanged(currentInt: Int, totalInt: Int, current: String, total: String) {}

        override fun onPlayPercentChanged(percent: Int) {}

        override fun onPlayStateChanged(state: Int) {
            mCurrentState = state
            mAdapter.setCurrentPlayState(state)
            /*if(mCurrentMusic != null && mCurrentMusic?.idOfBooks() == mViewModel.mData?.idOfBook()){
                when (state) {
                    UserWatcher.MusicStateWatcher.STATE_STOPED -> {
                    }
                    UserWatcher.MusicStateWatcher.STATE_PLAYING -> {
                    }
                    UserWatcher.MusicStateWatcher.STATE_COMPLETE -> {
                    }
                    UserWatcher.MusicStateWatcher.STATE_DISABLE -> {
                    }
                    else -> {}
                }
            }*/
        }

        override fun onPlaySpeedChanged(speed: Float) {}

        override fun onPlayListChanged() {}
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: SubscriptionChangedEvent) {
        mViewModel.setSubscription(event)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: LoginSuccessEvent) {
        flagToRefresh = true
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: LogoutEvent) {
        flagToRefresh = true
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
        Kukoo.watcher.register(mWatcher)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        Kukoo.watcher.unregister(mWatcher)
    }
}